import 'dart:async';
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:mybase/base/tool/empty/FFEmpty.dart';
import 'package:path_provider/path_provider.dart';

class FFAssetFile {
  /**
   * 从Asset获取文件
   * asset: xx/xx/file.json
   */
  static Future<File> fileByAssets(String assetPath) async {
    assert(!FFEmpty.stringIsEmpty(assetPath), "FFAssetFile。fileByAssets 目录不能为空");

    Completer<File> completer = Completer();
    String filename = assetPath.split(Platform.pathSeparator).last;

    try {
      var dir = await getApplicationDocumentsDirectory();
      File file = File("${dir.path}/$filename");
      var data = await rootBundle.load(assetPath);
      var bytes = data.buffer.asUint8List();
      await file.writeAsBytes(bytes, flush: true);
      completer.complete(file);
    } catch (e) {
      throw Exception('Error parsing asset file! err = $e');
    }

    return completer.future;
  }

  /**
   * 从Asset获取文件
   * asset:xx/xx/file.json
   * filename: file.json
   */
  static Future<File> fileByAsset(String asset, String filename) async {
    // To open from assets, you can copy them to the app storage folder, and the access them "locally"
    Completer<File> completer = Completer();

    try {
      var dir = await getApplicationDocumentsDirectory();
      File file = File("${dir.path}/$filename");
      var data = await rootBundle.load(asset);
      var bytes = data.buffer.asUint8List();
      await file.writeAsBytes(bytes, flush: true);
      completer.complete(file);
    } catch (e) {
      throw Exception('Error parsing asset file! err = $e');
    }

    return completer.future;
  }
}
